package com.lance.answer.question_answer.xj_new;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lance.answer.dto.CompleteInfo;
import com.lance.answer.dto.CourseInfo;
import com.lance.answer.dto.ScoreInfo;
import com.lance.answer.dto.XjUserCourseInfo;
import com.lance.answer.gui.answer.AnswerObject;
import com.lance.answer.gui.answer.DealJsonString;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.HttpUtil;
import com.lance.answer.util.XinJiangUtil;
import com.lance.answer.util.image_valid.VerifyCodeUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

/**
 * @author fengx
 * 新疆一体化答题-考试
 *
 * </p>
 */

@Slf4j
public class GetXJAnswerTestingScoreTask extends Thread{


    private static List<WebElement> findWeElements(WebDriver driver, String cssSelector, int second) {
        return (new WebDriverWait(driver, Duration.ofSeconds(second))).until((ExpectedCondition<List<WebElement>>) d -> {
            assert d != null;
            return d.findElements(By.cssSelector(cssSelector));
        });
    }

    private String driverPath;
    private LinkedBlockingDeque<CourseInfo> userCourses;

    public GetXJAnswerTestingScoreTask(String driverPath, LinkedBlockingDeque<CourseInfo> userCourses) {
        this.driverPath = driverPath;
        this.userCourses = userCourses;
    }

    @SneakyThrows
    @Override
    public void run() {

        while (userCourses.size() > 0) {
            CourseInfo courseInfo = userCourses.take();
            String userName = courseInfo.getUser();
            String password = courseInfo.getPwd();
            String subjectName = courseInfo.getSubjectName();
            int openCourseId = courseInfo.getOpenCourseId();
            Map<String, AnswerObject> answerMap = courseInfo.getAnswerMap();
            log.info("任务：{} 剩余 {} 行，当前课程：{} 用户名：{} 密码：{}",
                    Thread.currentThread().getName(),userCourses.size(),subjectName,userName, password);
            completeHomework(subjectName, openCourseId, answerMap, userName, password);
            //log.info("{} 开始执行刷题任务",Thread.currentThread().getName());

        }

        if (userCourses.size() == 0) {
            log.info("课程所有用户均已执行完毕，系统将在20min后结束");
            TimeUnit.MINUTES.sleep(20);
            return;
        }
    }




    public static void completeHomework(String majorName, int openCourseId, Map<String, AnswerObject> answerMap, String username, String pwd) throws IOException {

        boolean isComplete = false;

        try {

//            String filePath = "E:\\answerInfo一体化\\" + majorName + "\\" + username + "-testing.txt";
//            File userCompleteInfoFile = new File(filePath);
//            InputStream inputStream = new FileInputStream(userCompleteInfoFile);
//            String completeInfoStr = IOUtils.toString(inputStream, "UTF-8");
//            List<CompleteInfo> completeInfoList = JSONObject.parseArray(completeInfoStr, CompleteInfo.class);
//            if (null != completeInfoList) {
//                for (CompleteInfo info : completeInfoList) {
//                    if ("该课程没有考试！".equals(info.getSummary())) {
//                        isComplete = true;
//                        break;
//                    }
//                }
//            }

     //       File f1 = new File("E:\\XjScoreInfo\\" + majorName + "\\" + username + "-score.txt");
//            if(f1.exists()&&f1.length()>100){
//                isComplete = true;
//            }
            try {
                List<ScoreInfo> scoreInfoList = JSON.parseArray(
                        IOUtils.toString(new FileInputStream("E:\\XjScoreInfo\\"+majorName+"\\"+username+"-score.txt"),
                                StandardCharsets.UTF_8),ScoreInfo.class);
                if (scoreInfoList.get(0).getContent().getItems().get(0).getSumScore() >= 60) {
                    isComplete = true;
                }
            }catch (Exception ee){
            }


        } catch (Exception e) {
            // e.printStackTrace();
        }
        if (isComplete) {
            return;
        }
        WebDriver driver = Util.getDriver(null);

        List<ScoreInfo> scoreInfos = null;
        try {
            scoreInfos = Lists.newArrayList();
            int sid = 0;
            driver.get("https://xjskk.open.com.cn/stuspace-auth/#/login");
            XinJiangUtil.studentLogin(driver, username, pwd);
            Thread.sleep(2000);

            // FIXME 有的人报了多个专业
            try {
                WebElement we = findWeElements(driver, "div[class='part']", 20).get(0);
                // FIXME 正式要删掉
                String title = we.getAttribute("title");
                LinkedList<String> list = Lists.newLinkedList();
                list.add("2021年秋季");
                list.add("2021秋季");
                list.add("2021年春季");
                list.add("2021春季");
                list.add("2020年秋季");
                list.add("2020秋季");
                list.add("2020年春季");
                list.add("2020春季");
                list.add("2019年秋季");
                list.add("2019秋季");
                list.add("2019年春季");
                list.add("2019春季");
                for (String s : list) {
                    if (title.contains(s)) {
                        we.click();
                        break;
                    }
                }
            } catch (Exception e) {

            }

            Set<Cookie> cookies = driver.manage().getCookies();
            String studentSpaceProfile = Util.getStudentSpaceProfile2(cookies);
            String authorization = Util.getAuthorization2(cookies);
            Map<String, String> heads = Maps.newHashMap();
            String cookie = Util.getCookie(cookies);
            initHeads(heads, studentSpaceProfile, authorization);

            String getCourseInfoUrl = "https://xjskk.open.com.cn/api/student/student-space-service/courses/" + "getStudentCourses?pageNumber=1&pageSize=2000000&status=1&courseNameCode=";
            XjUserCourseInfo userCourseInfo = JSON.parseObject(HttpUtil.get(getCourseInfoUrl, cookie, heads), XjUserCourseInfo.class);
            for (XjUserCourseInfo.ContentDTO.ItemsDTO items : userCourseInfo.getContent().getItems()) {
                if (openCourseId == items.getOpenCourseId()) {
                    sid = items.getSelectCourseId();
                    break;
                }
            }

            driver.get("https://xjskk.open.com.cn/stuspace/#/course?oId=" + openCourseId + "&sId=" + sid);

            // 获取当前已经刷了的课程项目
            Thread.sleep(5000);
            for (WebElement liWe : findWeElements(driver, "li[class='fl']", 30)) {
                if ("考试".equals(liWe.getText().trim())) {
                    liWe.click();
                    break;
                }
            }
            Thread.sleep(5000);


            // https://xjskk.open.com.cn/api/student/student-space-service/testExam/getMyExamList?pageNumber=1&pageSize=20&name=&openCourseIdListStr=30914&type=2&testExamStatus=

            String getScoreInfo = "https://xjskk.open.com.cn/api/student/student-space-service/testExam/getMyExamList?pageNumber=1&pageSize=20&name=&openCourseIdListStr="
                    + openCourseId + "&type=2&testExamStatus=";
            try {
                ScoreInfo scoreInfo = JSON.parseObject(HttpUtil.get(getScoreInfo, cookie, heads), ScoreInfo.class);
                scoreInfos.add(scoreInfo);
            } catch (Exception e11) {

            }

            //   Thread.sleep(2000000);


        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Exception !!!!!!!!!!!!!!!!!");
        } finally {

            FileUtils.write(new File("E:\\XjScoreInfo\\" + majorName + "\\" + username + "-score.txt"), JSONObject.toJSONString(scoreInfos, SerializerFeature.PrettyFormat), "utf-8");
            closeDriver(driver);
        }
    }


    private static void closeDriver(WebDriver driver) {
        try {
            driver.close();
            driver.quit();
        } catch (Exception e) {

        }
    }






    public static void initHeads(Map<String, String> heads, String studentSpaceProfile, String authorization) {
        heads.put("referer", "https://xjskk.open.com.cn/stuspace/");
        heads.put("authority", "xjskk.open.com.cn");
        heads.put("path", "/api/student/student-space-service/resources/updateResourceTrace");
        heads.put("scheme", "scheme");
        heads.put("open-student-space-profile", studentSpaceProfile);
        heads.put("origin", "https://xjskk.open.com.cn");
        heads.put("authorization", authorization);
    }





}
